﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CaptchaLearning.Painter
{
    /// <summary>
    /// Interaction logic for Painter.xaml
    /// </summary>
    public partial class Painter : Window
    {
        /// <summary>
        /// Tên ký tự đang vẽ
        /// </summary>
        public string Name { get; set; }

        public BitmapImage Image { get; set; }

        /// <summary>
        /// Kiểm tra người dùng save hay thoát
        /// </summary>
        public bool Save { get; set; }

        public Painter()
        {
            InitializeComponent();

            Save = false;
        }

        /// <summary>
        /// Save ký tự vừa vẽ xuống file hình tạm với tên character.bmp
        /// </summary>
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            int margin = (int)this.inkCanvas.Margin.Left;
            int width = (int)this.inkCanvas.ActualWidth - margin;
            int height = (int)this.inkCanvas.ActualHeight - margin;

            RenderTargetBitmap rtb =
                    new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Default);
            rtb.Render(inkCanvas);

            BmpBitmapEncoder encoder = new BmpBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(rtb));
            byte[] bitmapBytes;
            using (MemoryStream ms = new MemoryStream())
            {
                encoder.Save(ms);
                ms.Position = 0;
                bitmapBytes = ms.ToArray();
            }
            if (Image != null)
                Image.StreamSource.Dispose();
            if (File.Exists(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Image", Name + ".bmp")))
                File.Delete(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Image", Name + ".bmp"));
            TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
            Bitmap bitmap = (Bitmap)tc.ConvertFrom(bitmapBytes);
            if(!Directory.Exists(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Image")))
                Directory.CreateDirectory(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Image"));
            bitmap.Save(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Image", Name + ".bmp"));

            Save = true;
            this.Close();
        }

        /// <summary>
        /// Xóa màn hình vẽ
        /// </summary>
        private void Clear_Click(object sender, RoutedEventArgs e)
        {
            Save = false;
            this.inkCanvas.Strokes.Clear();
        }
    }
}
